import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Form, Input, Modal, Checkbox, Button } from 'antd';
import { FormInstance } from 'antd/lib/form';

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const mapStateToProps = (state: any) => ({
  knowledgeAccessManage: state.knowledgeAccessManage,
  // loading: state.loading.effects['knowledgeAccessManage/postObjWithRes'],
});
class AccessManageModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      checkAllState: false,
      accessData: [],
      access: []
    }
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  setData = (record: any) => {
    const { dispatch } = this.props;
    this.formRef.current?.setFieldsValue({
      userAccount: record.accountName || '',
      userId: record.accountSid || '',
    })
    
    dispatch({
      type: 'http/getFetchPage',
      payload: { url: '/mscontent/knowledge/major/list', pageNo: 1, pageSize: 9999 },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const tempList = res.data?.list && res.data?.list.map((item: any) => {
            const { id, majorCode, name, description } = item;
            return {
              label: name,
              value: id,
              majorCode,
              description
            }
          })
          let status = record.majorIds?.length === tempList?.length; 
          this.setState({
            accessData: tempList || [],
            access: record.majorIds,
            checkAllState: status,
          })
        }
      }
    });
  }

  //  取消操作
  cancel = () => {
    const { closeModal } = this.props;
    closeModal();
    this.resetData();
  }

  resetData = () => {
    this.setState({
      accessData: [],
      access: [],
      checkAllState: false,
    })
    this.formRef.current?.resetFields();
  }

  //  保存操作
  save = () => {
    this.formRef.current?.submit();
  }

  //  提交数据
  ok = (values: any) => {
    const { handleRefresh, closeModal, dispatch } = this.props;
    const { access } = this.state 
    if (access && access.length <= 0) {
      message.warning('请至少选择一个专业');
      return false;
    }
    dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/mscontent/knowledge/authority/save',
        ...values,
        majorIds: access
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          message.success('操作成功');
          closeModal();
          handleRefresh();
          this.resetData();
        }
      }
    })
  }

  checkAll = (all: boolean) => {
    const { accessData } = this.state;
    let tempList: Array<any> = [];
    if (all) {
      accessData.forEach((item: any) => {
        tempList.push(item.value);
      });
    }
    this.setState({
      checkAllState: all,
      access: tempList
    })
  }

  onAccessCheckChange = (list: any) => {
    const { accessData } = this.state;
    this.setState(
      {
        checkAllState: list.length === accessData.length,
        access: list
      }
    )
  }

  render() {
    const { modalVisible } = this.props;
    const { checkAllState, accessData, access } = this.state
    const footer = (
      <div>
        <Button size="small" onClick={this.cancel}>
          取消
        </Button>
        {/* loading={loading} */}
        <Button size="small" onClick={this.save} type="primary">
          保存
        </Button>
      </div>
    );

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };

    return (
      <Modal
        style={{ top: 20 }}
        footer={footer}
        width={700}
        title="专业信息"
        visible={modalVisible}
        onCancel={this.cancel}
      >
        <Form
          style={{ marginTop: 12 }}
          ref={this.formRef}
          onFinish={this.ok}
        >
          <FormItem
            noStyle
            label=" "
            name="userId"
            rules={[]}
          >
            <Input type="hidden"/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="用户账号"
            name="userAccount"
            rules={[{ required: true, message: '请输入用户账号账号' }]}
          >
            <Input type="input" disabled />
          </FormItem>
          <Form.Item
            label="专业名称"
            {...formItemLayout}>
            <Checkbox checked={checkAllState} onChange={e => this.checkAll(e.target.checked)}>
              全选
            </Checkbox>
          </Form.Item>
          <Form.Item
            label=" "
            colon={false}
            name="specialty"
            {...formItemLayout}>
            <div style={{ width: '100%', padding: '10px', border: '1px solid #C3C3C3' }}>
              <CheckboxGroup
                options={accessData}
                value={access}
                onChange={this.onAccessCheckChange}
              />
            </div>
          </Form.Item>

        </Form>
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(AccessManageModal);
